<template>
  <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
    <!-- 头部 -->
    <home-head/>
    <!-- /头部 -->
    <div class="wrap">
      <!-- 轮播 -->
      <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item v-for="banner in banners" :key="banner.id">
          <img :src="banner.picUrl" alt="">
        </van-swipe-item>
      </van-swipe>
      <!-- /轮播 -->
      <!-- 宫格导航 -->
      <van-grid clickable :column-num="3">
        <van-grid-item
          v-for="cate in cates"
          :key="cate.id"
          :icon="cate.icon"
          :text="cate.name"
          :to="`/itemLists/${cate.id}`"
          />
      </van-grid>
      <!-- 导航导航 -->
      <!-- 推荐商品 -->
      <recommend @clickItem="enterDetail" @addCart="addCart" :items="items"/>
      <!-- /推荐商品 -->
    </div>
    <my-tabbar/>
  </van-pull-refresh>
</template>

<script>
import MyTabbar from '../../components/MyTabbar.vue'
import HomeHead from './components/HomeHead.vue'
import Recommend from './components/Recommend'
import { fetchBanner, fetchCates, fetchItems } from '@api'
import addCart from '@mixins/addCart'

export default {
  name: '首页',
  mixins: [addCart],
  data () {
    return {
      banners: [],
      cates: [],
      items: [],
      isLoading: false
    }
  },
  created () {
    this.fetchBanner()
    this.fetchCates()
    this.fetchItems()
  },
  methods: {
    enterDetail (id) {
      // 进入详情页
      this.$router.push({
        path: '/detail',
        query: {
          itemId: id
        }
      })
    },
    onRefresh () {
      // 用户下拉刷新了
      this.fetchItems()
    },
    fetchBanner () { // 获取轮播数据
      fetchBanner().then(res => {
        if (res.data.code === 0) {
          this.banners = res.data.data
        }
      })
    },
    fetchCates () { // 请求分类数据
      fetchCates().then(res => {
        if (res.data.code === 0) {
          this.cates = res.data.data
        }
      })
    },
    fetchItems () {
      // 请求首页推荐商品数据
      fetchItems({
        categoryId: 72399
      }).then(res => {
        console.log(res)
        this.isLoading = false
        if (res.data.code === 0) {
          this.items = res.data.data
        }
      })
    }
  },
  components: {
    MyTabbar,
    HomeHead,
    Recommend
  }
}
</script>

<style lang="scss" scoped>
.wrap{
  margin: 50px 0;
  .my-swipe img{
    width: 100%;
  }
  /deep/ .van-grid-item__text{
    color:#333;
  }
}

</style>
